package com.ojoin.trade.supplyloan_core.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.TaskService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ojoin.trade.bpm.web.domain.DefaultBpmEntity;
import com.ojoin.trade.bpm.web.service.BpmTaskService;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.ControllerException;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.SMSSendUtil;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.URLUtils;
import com.ojoin.trade.common.utils.UUIDUtils;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.NotificationTemplate;
import com.ojoin.trade.common.web.domain.Pair;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common.web.service.impl.NotificationTemplateService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoCheckService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.constdef.ISLFileType;
import com.ojoin.trade.supplyloan_core.web.domain.Order;
import com.ojoin.trade.supplyloan_core.web.domain.SlAutoRepayParam;
import com.ojoin.trade.supplyloan_core.web.domain.SlCreditRenewedVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbApplicationExpireVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlCreditInfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlFinanceinfoVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplication;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplicationInfoVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplicationStatVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditAggVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditLog;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlNotPayBackCreditForFront;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUserVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.service.TbSlAlipayInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlCreditInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlFinanceinfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanApplicationService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlProcessInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyInventoryService;
import com.ojoin.trade.supplyloan_core.web.service.impl.QueueSenderServieImpl;

/**
 * 保理员后台页面Controller
 */
@Controller
@RequestMapping("/operate")
public class OperatorSlLoanApplicationController extends SimpleBaseController {

	private Logger log = LoggerFactory
			.getLogger(OperatorSlLoanApplicationController.class);

	@Autowired
	private AccountBaseService accountservice;
	
	@Autowired
	private TbSlLoanApplicationService tbSlLoanApplicationService;

	@Autowired
	private TbSlPlatformUserService tbSlPlatformUserService;
	
	@Autowired
	private TbMerchantInfoBaseService tbMerchantInfoBaseService;
	
	@Autowired
	private TbSlFinanceinfoService finService;
	
	@Autowired
	private TbUploadFileService uploadService;
	
	@Autowired
	private MerchantUserBaseService userService;

	@Autowired
	private TbMerchantInfoCheckService tbMerchantInfoCheckService;
	
	@Autowired
	private TbSlLoanService loanService;
	
	@Autowired
	private TbSlLoanCreditService creditService;
	
	@Autowired
	private TbSlCreditInfoService creditInfoService;
	
	@Autowired
    private TbSlAlipayInfoService slAlipayInfoService; 
	
    @Autowired
    private TbUploadFileService uploadFileService;
    
	@Autowired
	private BpmTaskService bpmTaskService;
	
	@Autowired
	private TaskService taskService;
	
    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;
    
    @Autowired
    private TbSlSupplyInventoryService inventoryService;
    
    @Autowired
    private NotificationTemplateService notificationTemplateService;
    
    @Autowired
    private IRSAService rsaSrv;
    
    @Autowired  
    @Qualifier("creditLogQueueDestination")  
    private Destination destination;  
	
    @Autowired
	protected QueueSenderServieImpl queueSenderServie;
    
    @Autowired
	@Qualifier("catchDataTask")
	private Destination catchDataTask;
    
	@ResponseBody
	@RequestMapping(value = "/mhtToken", method = RequestMethod.GET)
	public Result mhtToken(HttpServletRequest request,String mhtNo) {
			List list = userService.preRealNameByPayUser(mhtNo);
			Map<String, String> data = (Map) list.get(1);
			if (CommonUtils.isSuccess(list)) {
				return new Result(Status.OK, data);
			} else {
				return CommonUtils.buildError(list);
			}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryMerchantInfoByJoinuserId", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryMerchantInfoByJoinuserId(HttpServletRequest request,
			@RequestParam int joinuserid) {
		try {
			TbMerchantInfo infovo = tbMerchantInfoBaseService
					.queryInfoByJoinId(joinuserid);
			return new Result(Result.Status.OK, infovo);
		} catch (Exception e) {
			log.error("查询joinuserid->" + joinuserid + "的实名认证信息出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "查询joinuserid->" + joinuserid + "的实名认证信息出错,请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/querySLLoanAppInfoListByStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result querySLLoanAppInfoListByStatus(HttpServletRequest request,
			@RequestParam int loanstatus, Pageable page) {
		try {
			List<TbSlLoanApplicationInfoVO> list = tbSlLoanApplicationService
					.querySLLoanAppInfoListByStatus(loanstatus, page);
			return new Result(Result.Status.OK, list);
		} catch (Exception e) {
			log.error("根据状态" + loanstatus + "查询供应链贷申请记录出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "根据状态" + loanstatus
					+ "查询供应链贷申请记录出错,请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryCreditedSLLoanAppInfoList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryCreditedSLLoanAppInfoList(HttpServletRequest request,
			@RequestParam int loanstatus, Pageable page) {
		try {
			List<TbSlLoanApplicationInfoVO> list = tbSlLoanApplicationService
					.queryCreditedSLLoanAppInfoList(loanstatus, page);
			return new Result(Result.Status.OK, list);
		} catch (Exception e) {
			log.error("根据状态" + loanstatus + "查询供应链贷申请记录出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "根据状态" + loanstatus
					+ "查询供应链贷申请记录出错,请重试");
		}
	}
	
    @ResponseBody
    @RequestMapping(value = "/querySLLoanMortagageFlagByJoinuserid", method = RequestMethod.GET)
    public Result querySLLoanMortagageFlagByJoinuserid(
            HttpServletRequest request,
            HttpServletResponse response,int joinuserid) {
    	TbSlLoanApplication slloanvo = tbSlLoanApplicationService.queryTbSlApplicationByJoinId(joinuserid);
    	return new Result(Status.OK, slloanvo==null?"":slloanvo.getMortgageFlag());
    }
    
    @ResponseBody
    @RequestMapping(value = "/querySLLoanAppInfoByJoinuserid", method = RequestMethod.GET)
    public Result querySLLoanAppInfoByJoinuserid(
            HttpServletRequest request,
            HttpServletResponse response,int joinuserid) {
    	TbSlLoanApplication slloanvo = tbSlLoanApplicationService.queryTbSlApplicationByJoinId(joinuserid);
    	return new Result(Status.OK, slloanvo);
    }

	@ResponseBody
	@RequestMapping(value = "/querySlLoanApplyStatListByStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result querySlLoanApplyStatListByStatus(HttpServletRequest request,
			@RequestParam int loanstatus, Pageable page) {
		try {
			int operatorJoinuserID = TradeUtils.getOperatorCompany(request);
			List<TbSlLoanApplicationStatVO> list = tbSlLoanApplicationService
					.querySlLoanApplyStatListByStatus(loanstatus, operatorJoinuserID, page);
			return new Result(Result.Status.OK, list);
		} catch (Exception e) {
			log.error("根据状态" + loanstatus + "查询供应链贷申请记录出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "根据状态" + loanstatus
					+ "查询供应链贷申请记录出错,请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/selectAllPlatformUserListByJoinID", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result selectAllPlatformUserListByJoinID(HttpServletRequest request,
			@RequestParam int joinuserid, Pageable page) {
		try {
			List<TbSlPlatformUserVO> list = tbSlPlatformUserService
					.selectAllPlatformUserListByJoinID(joinuserid, page);
			return new Result(Result.Status.OK, list);
		} catch (Exception e) {
			log.error("查询join用户" + joinuserid + "的所有电商平台账号出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "查询join用户" + joinuserid
					+ "的所有电商平台账号出错,请重试");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/selectAllSLLoanCreditAggVOByJoinID", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result selectAllSLLoanCreditAggVOByJoinID(HttpServletRequest request,
			@RequestParam int joinuserid) {
		try {
			TbSlLoanCreditAggVO aggvo = tbSlLoanApplicationService.selectAllSLLoanCreditAggVOByJoinID(joinuserid);
			return new Result(Result.Status.OK, aggvo);
		} catch (Exception e) {
			log.error("查询join用户" + joinuserid + "的所有授信信息出错,请重试", e);
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "查询join用户" + joinuserid
					+ "的所有授信信息出错,请重试");
		}
	}
	
    @ResponseBody
    @RequestMapping(value="/bindFinaceaccount",method = RequestMethod.POST)
     public Result bindFinaceaccount(HttpServletRequest request, @RequestBody TbSlPlatformUser uservo){
        if(CommonUtils.isEmpty(uservo.getId())){
            return new Result(Status.ERROR,"授信平台不能为空");
        }
        if(CommonUtils.isEmpty(uservo.getIdOfFinaceaccount())){
            return new Result(Status.ERROR,"关联的银行账号不能为空");
        }
        try{

       tbSlPlatformUserService.updateByIdSelective(uservo);
        return new Result(Status.OK,"管理金融户成功");
        }catch (Exception e){
          LogUtils.error(log,e,"关联金融户报错");
        }
        return new Result(Status.ERROR,"关联金融户报错");
    }
    
	@ResponseBody
	@RequestMapping(value = "/saveSLLoanCreditAggVO", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result saveSLLoanCreditAggVO(HttpServletRequest request,
		@RequestBody TbSlLoanCreditAggVO aggvo,
		@RequestParam(required = false) String taskid,
		@RequestParam(required = false) String processid) {
		
		TbMerchantInfo minfo = tbMerchantInfoBaseService.queryInfoByJoinId(aggvo.getApplyvo().getIdOfTbMerchantUser());
		if (!(minfo != null && minfo.getRealStatus() != null && CommonUtils.getInt(minfo.getRealStatus()) == IConstDef.REALNAME_STATUS_PASS)) {
			throw new BusinessException("该商户的实名认证未通过，请认证通过后再授信.");
		}
		
		if (StringUtils.isEmpty(aggvo.getShortname()))
			throw new BusinessException("商户简称不能为空.");
		
		if (aggvo.getApplyvo() == null)
			throw new BusinessException("通用授信信息不能为空.");
		
		if (aggvo.getPlatformuserList() == null || aggvo.getPlatformuserList().size() == 0)
			throw new BusinessException("电商平台授信信息不能为空.");
		
		aggvo.getApplyvo().setIdOfTbMerchantUserOfCreditor(TradeUtils.getOperatorCompany(request));
		
		//校验字段是否为空
		List<String> applyValidFieldNames = new ArrayList<String>();
		applyValidFieldNames.add("id");
		applyValidFieldNames.add("idOfTbMerchantUser");
		applyValidFieldNames.add("idOfTbMerchantUserOfCreditor");
		applyValidFieldNames.add("renewedServicefee");
		applyValidFieldNames.add("renewedFee");
		applyValidFieldNames.add("renewedRate");
//		applyValidFieldNames.add("creditEndDate");//保理合同审核时填入
		applyValidFieldNames.add("penalty");
		applyValidFieldNames.add("rowUpdateTime");
		applyValidFieldNames.add("yyzzExpireDate");
		List<Pair> applyValidBean = CommonUtils.beanValid(aggvo.getApplyvo(), applyValidFieldNames);
		if(CollectionUtils.isNotEmpty(applyValidBean)){
			return new Result(Result.Status.ERROR, (String) ((Pair)(applyValidBean.get(0))).second);
		}
		
		for(TbSlPlatformUserVO platformUserVO : aggvo.getPlatformuserList()) {
			try{
				if (!StringUtils.isEmpty(platformUserVO.getMaxAmount())) {
					int max_amount_int = Integer.parseInt(platformUserVO.getMaxAmount());
				}
			} catch(Exception e) {
				return new Result(Status.ERROR, "最高融资额度输入有误，金额" + platformUserVO.getMaxAmount() + "非整数或者太大，请检查.");
			}
			
			String maxAmount = CommonUtils.getString(CommonUtils.getLong(platformUserVO.getMaxAmount()) * 100);
			platformUserVO.setMaxAmount(maxAmount);
			
			//校验字段是否为空
			List<String> platformValidFieldNames = new ArrayList<String>();
			platformValidFieldNames.add("id");
			platformValidFieldNames.add("idOfTbMerchantUser");
			platformValidFieldNames.add("discount");
			platformValidFieldNames.add("rate");
			platformValidFieldNames.add("fee");
//			platformValidFieldNames.add("creditCertificate");//0328 不需要上传授信凭证
			platformValidFieldNames.add("maxAmount");
			platformValidFieldNames.add("loanPeriod");
			platformValidFieldNames.add("rowUpdateTime");
			platformValidFieldNames.add("contractExpireDate");
			List<Pair> platformValidBean = CommonUtils.beanValid(platformUserVO, platformValidFieldNames);
			if(CollectionUtils.isNotEmpty(platformValidBean)){
				return new Result(Result.Status.ERROR, (String) ((Pair)(platformValidBean.get(0))).second);
			}
		}
		
		tbSlLoanApplicationService.saveSLLoanCreditAggVO(aggvo, taskid, processid);
		
		return new Result(Result.Status.OK, aggvo);
	}
	
	@ResponseBody
	@RequestMapping(value = "/slVagueCredit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result slVagueCredit(HttpServletRequest request,
			@RequestBody TbSlLoanApplication vo,
			@RequestParam String taskid,
			@RequestParam String processid) {
		try {
			try{
				if (!StringUtils.isEmpty(vo.getMaxAmount())) {
					int max_amount_int = Integer.parseInt(vo.getMaxAmount());
				} else {
					return new Result(Status.ERROR, "最高融资额度不可为空.");
				}
			} catch(Exception e) {
				return new Result(Status.ERROR, "最高融资额度输入有误，非整数或者金额" + vo.getMaxAmount() + "太大，请检查.");
			}
			
			String maxAmount = CommonUtils.getString(CommonUtils.getLong(vo.getMaxAmount()) * 100);
			int operatorJoinuserid = TradeUtils.getOperatorCompany(request);
			vo.setMaxAmount(maxAmount);
			vo.setIdOfTbMerchantUserOfCreditor(operatorJoinuserid);
			
			//校验字段是否为空
			List<String> validFieldNames = new ArrayList<String>();
			validFieldNames.add("id");
			validFieldNames.add("idOfTbMerchantUser");
//			validFieldNames.add("discount");
			validFieldNames.add("rate");
			validFieldNames.add("fee");
			validFieldNames.add("loanPeriod");
//			validFieldNames.add("creditEndDate");//放到保理合同审核时填入
			validFieldNames.add("maxAmount");
			validFieldNames.add("idOfTbMerchantUserOfCreditor");
			validFieldNames.add("rowUpdateTime");
			validFieldNames.add("yyzzExpireDate");
			List<Pair> validBean = CommonUtils.beanValid(vo, validFieldNames);
			if(CollectionUtils.isNotEmpty(validBean)){
				return new Result(Result.Status.ERROR, (String) ((Pair)(validBean.get(0))).second);
			}
			
			tbSlLoanApplicationService.updateVagueCredit(vo, taskid, processid);
			
			sendMsg(vo.getIdOfTbMerchantUser(), ISLConstDef.VAGUE_CREDIT_PASS);
			return new Result(Result.Status.OK, "模糊授信成功.");
		} catch (BusinessException e) {
			log.error("模糊授信出错.");
			if (e instanceof BusinessException) { 
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "模糊授信出错.");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/slPlatformUserCredit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result slPlatformUserCredit(HttpServletRequest request,
			@RequestBody TbSlPlatformUser vo) {
		try {
			try{
				if (!StringUtils.isEmpty(vo.getMaxAmount())) {
					int max_amount_int = Integer.parseInt(vo.getMaxAmount());
				}
			} catch(Exception e) {
				return new Result(Status.ERROR, "最高融资额度输入有误，非整数或者金额超过21亿，请检查.");
			}
			
			String maxAmount = CommonUtils.getString(CommonUtils.getLong(vo.getMaxAmount()) * 100);
			vo.setMaxAmount(maxAmount);
			
			//校验字段是否为空
			List<String> validFieldNames = new ArrayList<String>();
			validFieldNames.add("id");
			validFieldNames.add("idOfTbMerchantUser");
			validFieldNames.add("discount");
			validFieldNames.add("rate");
			validFieldNames.add("fee");
			validFieldNames.add("creditCertificate");
			validFieldNames.add("maxAmount");
			validFieldNames.add("loanPeriod");
			validFieldNames.add("rowUpdateTime");
			validFieldNames.add("contractExpireDate");
			List<Pair> validBean = CommonUtils.beanValid(vo, validFieldNames);
			if(CollectionUtils.isNotEmpty(validBean)){
				return new Result(Result.Status.ERROR, (String) ((Pair)(validBean.get(0))).second);
			}
			
			tbSlPlatformUserService.updatePlatformUserCredit(vo);
			return new Result(Result.Status.OK, "电商平台用户授信成功.");
		} catch (BusinessException e) {
			log.error("电商平台用户授信出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "电商平台用户授信出错.");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/refuseCredit", method = RequestMethod.POST)
	public Result refuseCredit(HttpServletRequest request,
			@RequestParam int liveid, @RequestParam int joinuserid, 
			@RequestParam String credittype, 
			@RequestParam String returncredittype, 
			@RequestParam String memo,
			@RequestParam String taskid,
			@RequestParam String processid,
			@RequestParam String pagets) {
		try {
			if (StringUtils.isEmpty(memo)) {
				return new Result(Result.Status.ERROR, "拒绝授信原因不可为空.");
			}
			
			int idOfTbMerchantUserOfCreditor = TradeUtils.getOperatorCompany(request);
			tbSlLoanApplicationService.refuseCredit(liveid, joinuserid, ISLConstDef.SLLOANSTATUS_REFUSECREDITED, 
					credittype, returncredittype, idOfTbMerchantUserOfCreditor, memo, taskid, processid, pagets);
			
			if (credittype.equals("0")) {
				sendMsg(joinuserid, ISLConstDef.VAGUE_CREDIT_REFUSE);
			} else if (credittype.equals("1")) {
				sendMsg(joinuserid, ISLConstDef.PRECISE_CREDIT_REJECT);
			}
			return new Result(Result.Status.OK, "拒绝授信成功.");
		} catch (BusinessException e) {
			log.error("拒绝授信出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "拒绝授信出错.");
		}
	}

	private void sendMsg(int joinuserid, String type) {
		//开发环境不发短信通知
		if (CommonUtils.isDev())
			return;
		
		TbMerchantInfo infovo = tbMerchantInfoBaseService.queryInfoByJoinId(joinuserid);
		NotificationTemplate msgtemplate = notificationTemplateService.findByName(type);
		if (msgtemplate == null || StringUtils.isEmpty(msgtemplate.getTemplate())) 
			return;
		
		SMSSendUtil.sendMsg(infovo.getMobile(), msgtemplate.getTemplate());
	}
	
	@ResponseBody
	@RequestMapping(value = "/slUpdateCredit", method = RequestMethod.POST)
	public Result slUpdateCredit(HttpServletRequest request,
			@RequestBody TbSlLoanApplication vo) {
		try {
			//校验字段是否为空
			List<String> validFieldNames = new ArrayList<String>();
			validFieldNames.add("id");
			validFieldNames.add("idOfTbMerchantUser");
			validFieldNames.add("idOfTbMerchantUserOfCreditor");
			validFieldNames.add("renewedServicefee");
			validFieldNames.add("renewedFee");
			validFieldNames.add("renewedRate");
			validFieldNames.add("loanPeriod");
			validFieldNames.add("creditEndDate");
			validFieldNames.add("penalty");
			validFieldNames.add("rowUpdateTime");
			validFieldNames.add("yyzzExpireDate");
			List<Pair> validBean = CommonUtils.beanValid(vo, validFieldNames);
			if(CollectionUtils.isNotEmpty(validBean)){
				return new Result(Result.Status.ERROR, (String) ((Pair)(validBean.get(0))).second);
			}
			
			tbSlLoanApplicationService.updateCredit(vo);
			return new Result(Result.Status.OK, "修改授信成功.");
		} catch (BusinessException e) {
			log.error("修改授信出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "修改授信出错.");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/agreeMaterial", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result agreeMaterial(HttpServletRequest request,
			@RequestParam int liveid, 
			@RequestParam int joinuserid,
            @RequestParam int mortgage_flag,
            @RequestParam String mortgage_info, 
            @RequestParam String creditEndDate,
            @RequestParam String taskid,
			@RequestParam String processid,
            @RequestParam String pagets) {
		try {
			int idOfTbMerchantUserOfCreditor = TradeUtils.getOperatorCompany(request);
			tbSlLoanApplicationService.updateLoanStatusAndMortgageByIdWithTs(liveid, joinuserid, 
					idOfTbMerchantUserOfCreditor, ISLConstDef.SLLOANSTATUS_MATERIALPASSED, 
					mortgage_flag, mortgage_info, creditEndDate, 
					taskid, processid, pagets);
			
			sendMsg(joinuserid, ISLConstDef.CONTRACT_PASS);
			return new Result(Result.Status.OK, "保理合同审核成功.");
		} catch (BusinessException e) {
			log.error("保理合同审核通过出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "保理合同审核通过出错.");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/refuseMaterial", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result refuseMaterial(HttpServletRequest request,
			@RequestParam int liveid, 
			@RequestParam int joinuserid, 
			@RequestParam int idOfTbMerchantUserOfCreditor,
			@RequestParam String memo, 
			@RequestParam String taskid,
			@RequestParam String processid,
			@RequestParam String pagets) {
		try {
			if (StringUtils.isEmpty(memo)) {
				return new Result(Result.Status.ERROR, "保理合同审核不通过原因不可为空.");
			}
			
			tbSlLoanApplicationService.refuseMaterial(liveid, joinuserid, 
					ISLConstDef.SLLOANSTATUS_MATERIALREFUSEED, idOfTbMerchantUserOfCreditor,
					memo, taskid, processid, pagets);
			
			sendMsg(joinuserid, ISLConstDef.CONTRACT_REJECT);
			return new Result(Result.Status.OK, "保理合同审核不通过.");
		} catch (BusinessException e) {
			log.error("保理合同审核不通过报错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "保理合同审核不通过报错.");
		}
	}
	
	@ResponseBody
    @RequestMapping(value = "/queryRealNameInfo", method = RequestMethod.GET)
    public Result queryRealNameInfo(HttpServletRequest request,
			@RequestParam int joinuserid){
        TbMerchantInfo  info=tbMerchantInfoBaseService.selectRealnameInfoByJoinid(joinuserid);
       return new Result(Result.Status.OK,info);
         
    }
	
	@ResponseBody
    @RequestMapping(value = "/queryAllUserUnsuccessRefundTask", method = RequestMethod.GET)
    public Result queryRealNameInfo(HttpServletRequest request){
		List<TbSlFinanceinfoVO> list = finService.queryAllUserUnsuccessRefundTask();
       return new Result(Result.Status.OK,list);
    }
	
	@ResponseBody
	@RequestMapping(value = "/downloadSLContractFile", method = RequestMethod.GET)
	public void downloadSLContractFile( HttpServletRequest request, HttpServletResponse response, int liveid) throws IOException {
		TbSlLoanApplication livevo = tbSlLoanApplicationService.queryTbSlApplicationByID(liveid);
		if(null==livevo||StringUtils.isEmpty(livevo.getContract())){
			throw new ControllerException("不存在可下载的上下游贸易合同.");
		}
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(livevo.getContract()));
		String filename = IConstDef.DOWNLOAD_SLCONTRACTFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCONTRACTFILE);
	}

	@ResponseBody
	@RequestMapping(value = "/downloadSLContractInfoCheckFile", method = RequestMethod.GET)
	public void downloadSLContractInfoCheckFile(HttpServletRequest request, HttpServletResponse response, int liveid) throws IOException {
		TbSlLoanApplication livevo = tbSlLoanApplicationService.queryTbSlApplicationByID(liveid);
		if(null==livevo||StringUtils.isEmpty(livevo.getContract())){
			throw new ControllerException("不存在可下载的合同信息核查表.");
		}
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(livevo.getContract()));
		String filename = IConstDef.DOWNLOAD_SLCONTRACTFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCONTRACTFILE);
	}
	
	@ResponseBody
	@RequestMapping(value = "/downloadSLContractFileByPlatformUser", method = RequestMethod.GET)
	public void downloadSLContractFileByPlatformUser( HttpServletRequest request, HttpServletResponse response, int platformuserid) throws IOException {
		TbSlPlatformUser platformuser = tbSlPlatformUserService.queryById(platformuserid);
		if(null == platformuser || StringUtils.isEmpty(platformuser.getBusiContract())){
			throw new ControllerException("不存在可下载的上下游贸易合同.");
		}
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(platformuser.getBusiContract()));
		String filename = IConstDef.DOWNLOAD_SLCONTRACTFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCONTRACTFILE);
	}
	
	@ResponseBody
	@RequestMapping(value = "/downloadSLCreditInfoFile", method = RequestMethod.GET)
	public void downloadSLCreditInfoFile( HttpServletRequest request, HttpServletResponse response, int liveid) throws IOException {
		TbSlLoanApplication livevo = tbSlLoanApplicationService.queryTbSlApplicationByID(liveid);
		if(null==livevo||StringUtils.isEmpty(livevo.getCreditInformation())){
			throw new ControllerException("不存在可下载的模糊授信信息.");
		}
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(livevo.getCreditInformation()));
		
		String filename = IConstDef.DOWNLOAD_SLCREDITINFOFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCREDITINFOFILE);
	}
	
	@ResponseBody
	@RequestMapping(value = "/downloadSLCreditCertificateFile", method = RequestMethod.GET)
	public void downloadSLCreditCertificateFile( HttpServletRequest request, HttpServletResponse response, int platformuserid) throws IOException {
		TbSlPlatformUser uservo = tbSlPlatformUserService.queryById(platformuserid);
		if (uservo == null)
			throw new ControllerException("传入的电商平台账号不存在，请检查.");
		
		if(CommonUtils.isEmpty(uservo.getCreditCertificate())) {
			throw new ControllerException("电商平台账号" + platformuserid + "的授信凭证为空，请检查.");
		}
		
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(uservo.getCreditCertificate()));
		
		String filename = IConstDef.DOWNLOAD_SLCREDITCERTIFICATEFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator + uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCREDITCERTIFICATEFILE);
	
		
		}
	
	@ResponseBody
	@RequestMapping(value = "/downloadSLMaterialFile", method = RequestMethod.GET)
	public void downloadSLMaterialFile( HttpServletRequest request, HttpServletResponse response, int liveid) throws IOException {
		TbSlLoanApplication livevo = tbSlLoanApplicationService.queryTbSlApplicationByID(liveid);
		if(null==livevo||StringUtils.isEmpty(livevo.getMaterial())){
			throw new ControllerException("不存在可下载的保理合同.");
		}
		
		TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(livevo.getMaterial()));
		
		String filename = IConstDef.DOWNLOAD_SLUSERMATERIALFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLUSERMATERIALFILE);
	}
	
	/**
     * 上传授信凭证
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadCreditFile", method = RequestMethod.POST)
    public void uploadCreditFile(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "uploadCreditFile", required = false) MultipartFile file) throws IOException{
            Result res=CommonUtils.getPathUploadedFile(request, response, file, ISLConstDef.slLoanCreditFileDir);
            CommonUtils.sendJOSNResponse(response,res);
    }
	
    /**
     * 查询九盈用户的电商平台用户是否全部授信完成
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectUncreditPlatformUserByJoinuserId", method = RequestMethod.GET)
    public Result selectUncreditPlatformUserByJoinuserId(HttpServletRequest request,
			@RequestParam int joinuserid) throws IOException {
            int count = tbSlPlatformUserService.selectUncreditPlatformUserByJoinuserId(joinuserid);
            if (count  > 0) {
            	return new Result(Result.Status.ERROR, "该商户还有" + count + "个电商平台待分别授信，请完成后再进行公共信息授信.");
            }
            return new Result(Result.Status.OK, count);
    }
	
    /**
     * 更新用户的实名信息证件认证校验标记
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateCheckFlagByJoinuserId", method = RequestMethod.POST)
    public Result updateCheckFlagByJoinuserId(HttpServletRequest request,
			@RequestParam int joinuserid, 
			@RequestParam String type, 
			@RequestParam int flagvalue) throws IOException {
        int count = tbMerchantInfoCheckService.updateCheckFlagByJoinuserId(joinuserid, type, flagvalue);
        return new Result(Result.Status.OK, count);
    }
    
    /**
     * 推送用户实名信息到现在支付
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pushRealInfoByJoinuserId", method = RequestMethod.POST)
    public Result pushRealInfoByJoinuserId(HttpServletRequest request,
			@RequestParam int joinuserid, @RequestParam int realStatus) throws IOException {
    		tbMerchantInfoBaseService.pushRealInfoByJoinuserId(joinuserid, realStatus);
    		return new Result(Result.Status.OK, "商户" + joinuserid + "实名信息推送成功.");
    }
    
    /**
     * 未推送的：推送用户实名信息到现在支付
     * 已推送的：从现在支付更新实名状态
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pushAndSyncRealName", method = RequestMethod.POST)
    public Result pushAndSyncRealName(HttpServletRequest request,
			@RequestParam int joinuserid) throws IOException {
    	try{
    		TbMerchantUser uservo = userService.queryById(joinuserid);
    		List muserinfoList = userService.queryPayUserVOByID(uservo
    				.getUserIdOfIPayNow());
    		if (muserinfoList == null || muserinfoList.size() == 0) {
    			tbMerchantInfoBaseService.pushRealInfoByJoinuserId(joinuserid, 2);
    			return new Result(Result.Status.OK, "joinuserid->" + joinuserid + " 在现在支付未查到实名信息，已进行推送操作，请实名通过后再执行同步操作.");
    		} else {
    			tbMerchantInfoBaseService.syncRealName(joinuserid);
    			TbMerchantInfo infovo = tbMerchantInfoBaseService.queryInfoByJoinId(joinuserid);
    			return new Result(Result.Status.OK, "商户" + joinuserid + "实名信息同步成功, 实名状态->" + infovo.getRealStatus());
    		}
    	} catch(BusinessException e) {
    		return new Result(Result.Status.ERROR, e.getMessage());
    	}
    }
    
    /**
     * 从现在支付同步商户实名状态
     * @param request
     * @return
     */
    @RequestMapping(value = "/syncRealNameByJoinuserId", method = RequestMethod.POST)
    public Result syncRealNameByJoinuserId(HttpServletRequest request, @RequestParam int joinuserid){
        try{
            tbMerchantInfoBaseService.syncRealName(joinuserid);
            return new Result(Result.Status.OK, "商户" + joinuserid + "的实名数据更新成功");
        }catch (Exception e){
            log.error("同步实名信息失败",e);
            return new Result(Result.Status.ERROR,"数据更新失败，" + e.getMessage());
        }
    }
    
    
    /**
     * 更新天猫平台用户的支付宝绑定
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateBindAlipay", method = RequestMethod.POST)
    public Result updateBindAlipay(HttpServletRequest request,
			@RequestParam int joinuserid, @RequestParam String  platformType) throws IOException {
    		
    	
    		return new Result(Result.Status.OK, "操作成功");
    }
    
    /**
     * 预览上传的授信凭证
     * 
     * @param request
     * @param response
     * @param uploadfileid
     * @throws IOException
     */
    @ResponseBody
	@RequestMapping(value = "/previewSLCreditCertificateFile", method = RequestMethod.GET)
	public void previewSLCreditCertificateFile( HttpServletRequest request, HttpServletResponse response, int uploadfileid) throws IOException {
    	if(CommonUtils.isEmpty(uploadfileid)) {
			throw new ControllerException("上传的授信凭证为空，请检查.");
		}
		
		TbUploadFile uploadFileVO = uploadService.queryById(uploadfileid);
		String filename = IConstDef.DOWNLOAD_SLCREDITCERTIFICATEFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator + uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCREDITCERTIFICATEFILE);
	}
    
	@RequestMapping(value = "/downloadSLCheckAccountFile", method = RequestMethod.GET)
	public void downloadSLCheckAccountFile( HttpServletRequest request, HttpServletResponse response, int joinuserid) throws IOException {
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	loanService.exportSLLoanReportExcelFile(joinuserid, bos);
    	TbMerchantUser uservo = userService.queryById(joinuserid);
    	String filename = uservo.getShortname() + "供应链贷（对账表-" + TimeUtils.getCurDate() + "）.xls";
    	DownloadUtils.download(request, response, filename, bos.toByteArray());
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANCHECKACCOUNT);
	}
    
    /**
     * 更新指定电商平台的征信凭证
     *
     * @param request
     * @return
     */
	@ResponseBody
    @RequestMapping(value = "/updatePlatformUserCreditCheckInfo", method = RequestMethod.POST)
    public Result updatePlatformUserCreditCheckInfo(
            HttpServletRequest request, HttpServletResponse response, @RequestBody TbSlCreditInfo infovo) throws IOException{
    	
    	tbSlPlatformUserService.updatePlatformUserCreditCheckInfo(infovo);
    	return new Result(Result.Status.OK, "更新成功.");
            
    }
    
	/**
     * 更新九盈用户的所有电商平台的征信凭证
     *
     * @param request
     * @return
     */
	@ResponseBody
    @RequestMapping(value = "/updateMerchantUserCreditCheckInfo", method = RequestMethod.POST)
    public Result updateMerchantUserCreditCheckInfo(
            HttpServletRequest request, HttpServletResponse response, @RequestBody TbSlCreditInfo infovo) throws IOException{
    	
    	tbSlPlatformUserService.updateMerchantUserCreditCheckInfo(infovo);
    	return new Result(Result.Status.OK, "更新成功.");
            
    }
	
    /**
     * 下载付款通知书
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/downloadSLPaymentOrder", method = RequestMethod.GET)
    public void downloadSLPaymentOrder(
            HttpServletRequest request, HttpServletResponse response, 
            int joinuserid, Integer id, String procInsId) throws IOException{
        if(CommonUtils.isEmpty(id)){
            throw new BusinessException("待还贷款编号不能为空.");
        }
        
        //生成付款通知书，写入文件下载表，并更新流程id对应的多条放款记录的payment_notice
    	String downloadpath = tbSlLoanApplicationService.generateSLPaymentOrder(joinuserid, id, procInsId);
    	
    	String filename = IConstDef.DOWNLOAD_PAYMENTORDER + ".pdf";
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir() + File.separator + downloadpath, filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_PAYMENTORDER);
    }
    
    /**
     * 下载电商平台的征信信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/downloadPlatformUserCreditCheckInfo", method = RequestMethod.GET)
    public void downloadPlatformUserCreditCheckInfo(
            HttpServletRequest request, HttpServletResponse response, 
            int id_of_platformuser) throws IOException{
    	TbSlPlatformUser platformuservo = tbSlPlatformUserService.queryById(id_of_platformuser);
    	if (platformuservo == null) {
    		throw new BusinessException("查询不到对应的电商平台信息.");
    	}
    	String certificateID = platformuservo.getCreditcheckCertificate();
    	if(StringUtils.isEmpty(certificateID)) {
    		throw new BusinessException("电商平台" + id_of_platformuser + "的征信信息为空.");
    	}
    	
    	TbSlCreditInfo creditinfovo = creditInfoService.queryById(CommonUtils.getInt(certificateID));
    	if (creditinfovo == null) {
    		throw new BusinessException("征信信息编号" + id_of_platformuser + "的征信信息为空.");
    	}
    	
    	TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(creditinfovo.getCreditFile()));
		String filename = IConstDef.DOWNLOAD_SLCREDITCHECKCERTIFICATEFILE + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator + uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCREDITCHECKCERTIFICATEFILE);
    }
    
    
    @ResponseBody
    @RequestMapping(value = "/queryRenewedInfo",method = RequestMethod.GET)
    public Result queryRenewedInfo(HttpServletRequest request,Integer id,Integer joinid){

        try{
            SlCreditRenewedVo vo=tbSlLoanApplicationService.queryRenewedInfoByCredit(id,joinid);
            return new Result(Status.OK,vo);
            }catch (Exception e){
            LogUtils.error(log,e,"查询贷款的展期情况信息出错");
            if(e instanceof BusinessException){
                    return new Result(Status.ERROR,e.getMessage());

            }
            return new Result(Status.ERROR,"查询贷款的展期情况信息出错");
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/needBindAlipay", method = RequestMethod.POST)
    public Result needBindAlipay(HttpServletRequest request,Integer  id) {
        Map param=new HashMap();
        param.put("id", id);
        param.put("bindAlipay", "1");
        tbSlPlatformUserService.updateTbSlPlatFormUser(param);
        return new Result(Status.OK, "设置需要支付宝成功");
    }
    
    @ResponseBody
    @RequestMapping(value = "/unNeedBindAlipay", method = RequestMethod.POST)
    public Result unNeedBindAlipay(HttpServletRequest request,Integer  id) {
        Map param=new HashMap();
        param.put("id", id);
        param.put("bindAlipay", "0");
        tbSlPlatformUserService.updateTbSlPlatFormUser(param);
        return new Result(Status.OK, "取消需要支付宝成功");
    }

    /**
     * 下载合同信息核查表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/downloadSLContractInfoCheck", method = RequestMethod.GET)
	public void downloadSLContractInfoCheck( HttpServletRequest request, HttpServletResponse response, int joinuserid) throws IOException {
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	loanService.exportSLContractInfoCheckExl(joinuserid, bos);
    	String filename = "合同信息核查表-" + TimeUtils.getCurDate() + ".xls";
    	DownloadUtils.download(request, response, filename, bos.toByteArray());
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLCONTRACTINFOCHECK);
	}
   
    @ResponseBody
    @RequestMapping(value = "/downloadSlLoanMortgage", method = RequestMethod.GET)
    public void downloadSlLoanMortgage(
            HttpServletRequest request,
            HttpServletResponse response,int joinuserid) {
    	TbSlLoanApplication slloanvo = tbSlLoanApplicationService.queryTbSlApplicationByJoinId(joinuserid);
        if(!CommonUtils.isEmpty(slloanvo.getMortgageInfo())){
        	TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(slloanvo.getMortgageInfo()));
	        String filename = IConstDef.DOWNLOAD_SLMORTGAGEINFO + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
	        try {
	        	DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
	        }catch (Exception e) {
	        	LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_SLMORTGAGEINFO);
	        }
        }
    }
    
    
    @RequestMapping(value = "/baseCreditForm")
    public String baseCreditForm(DefaultBpmEntity bpmvo) {
        int id = bpmvo.getId();
		TbSlLoanApplication applyvo = tbSlLoanApplicationService.queryById(id);

		String procInsId = bpmvo.getBpm().getProcInsId();
		String taskId = bpmvo.getBpm().getTaskId();
		String taskDefKey = bpmvo.getBpm().getTaskDefKey();
		String status = bpmvo.getBpm().getStatus();

		Map<String,String> params=new HashMap<String,String>();
		params.put("joinuserid",String.valueOf(applyvo.getIdOfTbMerchantUser()));
		params.put("processid",procInsId);
		params.put("taskid",taskId);
		params.put("taskDefKey",taskDefKey);
		params.put("status",status);


        String view = "/operate/slplatform.html?"+ URLUtils.mapToQParams(params);
        // 查看审批申请单
        if (null != procInsId) {
            //自定义任务环节编号

            if (taskDefKey.equals("credit_auditRealnameInfo")) {
            	view = "/operate/autelist.html?" + URLUtils.mapToQParams(params);
            	return "redirect:"+ view;
            } else if (taskDefKey.equals("credit_slVagueCredit")) {
            	view = "/operate/slplatformvague.html?"+ URLUtils.mapToQParams(params);
            	return "redirect:"+ view;
            } else if (taskDefKey.equals("credit_slPreciseCredit")) {
            	view = "/operate/slplatformaccurate.html?" + URLUtils.mapToQParams(params);
            	return "redirect:"+ view;
            } else if (taskDefKey.equals("credit_riskApprove")) {
            	view = "/operate/slplatformaccurate.html?" + URLUtils.mapToQParams(params);
            	return "redirect:"+ view;
            }else if(taskDefKey.equals("credit_approveContract")){
                view = "/operate/Contractreview.html?"+ URLUtils.mapToQParams(params);
                return "redirect:"+ view;
            }
        }
        
        return null;
    }
    
    @ResponseBody
	@RequestMapping(value = "/riskCreditRefuse", method = RequestMethod.POST)
	public Result riskCreditRefuse(HttpServletRequest request,
			@RequestParam int liveid, @RequestParam int joinuserid, 
			@RequestParam int idOfTbMerchantUserOfCreditor, 
			@RequestParam String memo,
			@RequestParam String taskid,
			@RequestParam String processid,
			@RequestParam String pagets) {
		try {
			if (StringUtils.isEmpty(memo)) {
				return new Result(Result.Status.ERROR, "风控审核拒绝授信原因不可为空.");
			}
			tbSlLoanApplicationService.riskCreditRefuse(liveid, joinuserid, 
					 idOfTbMerchantUserOfCreditor, memo, taskid, processid, pagets);
			return new Result(Result.Status.OK, "风控审核拒绝授信成功.");
		} catch (BusinessException e) {
			log.error("风控审核拒绝授信出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "风控审核拒绝授信出错.");
		}
	}
    
    @ResponseBody
	@RequestMapping(value = "/riskCreditPassed", method = RequestMethod.POST)
	public Result riskCreditPassed(HttpServletRequest request,
			@RequestParam int liveid, @RequestParam int joinuserid,  
			@RequestParam int idOfTbMerchantUserOfCreditor, 
			@RequestParam String taskid,
			@RequestParam String processid,
			@RequestParam String pagets) {
		try {
			tbSlLoanApplicationService.riskCreditPassed(liveid, joinuserid, 
					 idOfTbMerchantUserOfCreditor, taskid, processid, pagets);
			
			sendMsg(joinuserid, ISLConstDef.PRECISE_CREDIT_PASS);
			return new Result(Result.Status.OK, "风控审核授信成功.");
		} catch (BusinessException e) {
			log.error("风控审核授信拒绝出错.");
			if (e instanceof BusinessException) {
				return new Result(Result.Status.ERROR, e.getMessage());
			}
			return new Result(Result.Status.ERROR, "风控审核授信拒绝出错.");
		}
	}
    @ResponseBody
    @RequestMapping(value="/queryWillExpireForApplication",method = RequestMethod.GET)
    public Result queryWillExpireForApplication(HttpServletRequest request,Pageable page){
        try{
            List<TbApplicationExpireVo> list=tbSlLoanApplicationService.queryApplicationExpireForOperator(page);
            return new Result(Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询快到期的合同和营业执照");
            return new Result(Status.ERROR,"查询失败");
        }
    }
    
    /**
     * 对账页面下载付款通知书
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/downloadSLPaymentOrderInCheckAccount", method = RequestMethod.GET)
    public void downloadSLPaymentOrderInCheckAccount(
            HttpServletRequest request, HttpServletResponse response, 
            int creditloanid) throws IOException{
        if(CommonUtils.isEmpty(creditloanid)){
        	CommonUtils.sendJOSNResponse(response, new Result(Status.WARNING, "贷款编号不能为空."));
			return;
        }
        TbSlLoanCreditLog creditlogvo = creditService.queryById(creditloanid);
        if(creditlogvo == null){
        	CommonUtils.sendJOSNResponse(response, new Result(Status.WARNING, "贷款编号->" + creditloanid + "对应贷款记录为空，请检查."));
			return;
        }
        
        if(StringUtils.isEmpty(creditlogvo.getPaymentNotice())) {
        	CommonUtils.sendJOSNResponse(response, new Result(Status.WARNING, "贷款编号->" + creditloanid + "对应贷款记录的付款通知书为空，请检查."));
			return;
        }
        
        //生成付款通知书，写入文件下载表，并更新流程id对应的多条放款记录的payment_notice
    	TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(creditlogvo.getPaymentNotice()));
    	String filename = IConstDef.DOWNLOAD_PAYMENTORDER + ".pdf";
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir() + File.separator + uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_PAYMENTORDER);
    }
    
    /**
     * 
     * 获得文件类型列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSLFileType", method = RequestMethod.GET)
    @ResponseBody
    public Result getSLFileType(
            HttpServletRequest request, HttpServletResponse response) throws IOException{
    	return new Result(Status.OK, ISLFileType.fileTypeMap);
    }
    
    /**
     * 根据条件查询文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getFileListByCondition", method = RequestMethod.GET)
    @ResponseBody
    public Result getFileListByCondition(
            HttpServletRequest request, HttpServletResponse response, 
            Integer joinuserid, String filetype, String platformtype,
            String startdate, String enddate, Pageable page) throws IOException{
        if(CommonUtils.isEmpty(joinuserid) && CommonUtils.isEmpty(filetype) && CommonUtils.isEmpty(platformtype)&& CommonUtils.isEmpty(startdate) && CommonUtils.isEmpty(enddate)){
            return new Result(Status.WARNING, "选择条件不可以全部为空.");
        }
        
    	List<TbUploadFile> filelist = uploadFileService.getFileListByCondition(joinuserid, filetype, platformtype, startdate, enddate,page);
    	return new Result(Status.OK, filelist);
    }
    
	@RequestMapping(value = "/downloadSLFileById", method = RequestMethod.GET)
	public void downloadSLFileById( HttpServletRequest request, HttpServletResponse response, Integer fileid) throws IOException {
		if(null == fileid){
			CommonUtils.sendJOSNResponse(response, new Result(Status.WARNING, "待下载文件id为空，请检查."));
			return;
		}
		
		TbUploadFile uploadFileVO = uploadService.queryById(fileid);
		String filename = ISLFileType.fileTypeMap.get(uploadFileVO.getFileType()) + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir() + File.separator + uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s", filename);
	}
	
	
	/**
     * 查询商户未放款的入库订单集合
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSlSupplyInventoryByPlatformuserid", method = RequestMethod.GET)
    @ResponseBody
    public Result getSlSupplyInventoryByPlatformuserid(
            HttpServletRequest request, 
            Integer platformuserid) throws IOException{
        if(CommonUtils.isEmpty(platformuserid)){
            return new Result(Status.WARNING, "商户平台id为空.");
        }
        
    	List<TbSlSupplyInventory> list = inventoryService.queryInventoryByRowCreateTime(platformuserid, null, null, TbSlSupplyInventory.IN);
    	return new Result(Status.OK, list);
    }
	
    /**
     * 更新商户未放款的入库订单集合的状态为已放款
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateSlSupplyInventoryListInPay", method = RequestMethod.GET)
    @ResponseBody
    public Result updateSlSupplyInventoryListInPay(
            HttpServletRequest request, 
            Integer[] inventoryids, String loan_code,Integer platformUserId) throws IOException{
//        if(CommonUtils.isEmpty(inventoryids)){
//            return new Result(Status.WARNING, "待更新入库单为空.");
//        }
//        
//        List<TbSlSupplyInventory> list = new ArrayList<TbSlSupplyInventory>();
//        for(Integer id : inventoryids) {
//        	TbSlSupplyInventory vo = new TbSlSupplyInventory();
//        	vo.setId(id);
//        	vo.setItemStatus(TbSlSupplyInventory.PAY);
//        	vo.setLoanCode(loan_code);
//        	list.add(vo);
//        }
//        
//    	inventoryService.updateJDBCBatch(list);
//    	
//    	// 重新统计可提款额
//    	Order order = new Order(Order.STATTOTAL);
//		order.getParames().put("platformUserId", platformUserId+"");
//		
//		queueSenderServie.send(catchDataTask, order);
//		
    	return new Result(Status.OK, "更新入库单状态为已融资成功.");
    }
    
    /**
     * 查询商户指定融资编号对应的入库订单集合
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectSlSupplyInventoryListByLoancode", method = RequestMethod.GET)
    @ResponseBody
    public Result selectSlSupplyInventoryListByLoancode(
            HttpServletRequest request, String loan_code) throws IOException{
    	TbSlSupplyInventory vo = new TbSlSupplyInventory();
    	vo.setLoanCode(loan_code);
    	List<TbSlSupplyInventory> list = inventoryService.queryList(vo);
    	return new Result(Status.OK, list);
    }
    
    //查询指定商户指定账户类型余额
  	@ResponseBody
  	@RequestMapping(value = "/queryAccountBalanceByMhtnoAndType", method = {RequestMethod.POST,RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
  	public Result queryAccountBalanceByMhtnoAndType(HttpServletRequest request, @RequestParam String mhtno, @RequestParam String acctype) {
  		try {
          	String balance = accountservice.queryBalance(mhtno, acctype);
              return new Result(Status.OK, balance);
  		} catch (Exception e) {
  			log.error("查询商户" + mhtno + "账户" + acctype + "余额报错", e);
  			if (e instanceof BusinessException)
  				return new Result(Status.ERROR, e.getMessage());
  			
  			return new Result(Status.ERROR, "查询商户" + mhtno + "账户" + acctype + "余额报错，请重试");
  		}
  	}
    
  		
    //手动为商户部分还款
  	@ResponseBody
    @RequestMapping(value = "/manualPartRefund", method = RequestMethod.POST)
    public Result manualPartRefund(HttpServletRequest request, @RequestParam String mhtno, @RequestBody SlAutoRepayParam param, @RequestParam String pageRefundAmount) {
        if (param==null ||param.getListvo()==null) {
            return new Result(Result.Status.ERROR, "未选择任何要还款的贷款记录");
        }

        try {
        	String finBalance = "100000000";
        	if(!CommonUtils.isDev()) {
        		finBalance = accountservice.queryBalance(mhtno, IConstDef.ACCTYPE_FINANCING);
        	}
            if (StringUtils.isEmpty(finBalance)) {
                return new Result(Result.Status.ERROR, "查询业务户余额为0，请到账后再还款");
            }
            if (CommonUtils.getLong(finBalance) < CommonUtils.getLong(pageRefundAmount))
                return new Result(Status.ERROR, "结算户金额不够，请检查.");
            
             String  pwd=rsaSrv.decryptStringByJs(param.getPwd());
            
             TbMerchantInfo infovo = tbMerchantInfoBaseService.queryInfoByMhtno(mhtno);
             loanService.manualPartRefund(infovo.getIdOfTbMerchantUser(), param.getListvo(), param.getLoanInfoVo(), pwd, finBalance, IConstDef.ACCTYPE_BASE);
             
            return new Result(Result.Status.OK, "手动部分还款成功.");
        } catch (Exception e) {
            LogUtils.error(log, e, "手动部分还款失败");
            if(e instanceof IPayNowException){
                return new Result(Status.WARNING,"处理中");
            }
            if (e instanceof BusinessException) {
                return new Result(Result.Status.ERROR, e.getMessage());
            }
            return new Result(Result.Status.ERROR, "手动部分还款失败");
        }
    }
  	
  	@ResponseBody
  	@RequestMapping(value = "/manualRechargeAccountToBase", method = {RequestMethod.POST,RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
  	public Result manualRechargeAccountToBase(HttpServletRequest request, @RequestParam String mhtno, @RequestParam String toBaseAccount) {
  		try {
  			String finBalance = "100000000";
        	if(!CommonUtils.isDev()) {
        		finBalance = accountservice.queryBalance(mhtno, IConstDef.ACCTYPE_FINANCING);
        	}
          	if (CommonUtils.getLong(finBalance) < CommonUtils.getLong(toBaseAccount))
              return new Result(Status.ERROR, "业务户金额不够，请检查.");
          	
          	if(!CommonUtils.isDev()) {
	          	String orderId = UUIDUtils.create();
	          	accountservice.rechargeAccountBalanceNoPwd(mhtno, IConstDef.ACCTYPE_FINANCING, mhtno, IConstDef.ACCTYPE_BASE, toBaseAccount, "转账至基本户", orderId);
          	}
          	return new Result(Result.Status.OK, "从业务户转账" + CommonUtils.getFenByString(toBaseAccount)+ "至基本户成功.");
  		} catch (Exception e) {
  			log.error("商户" + mhtno + "从业务户转账" + CommonUtils.getFenByString(toBaseAccount)+ "至基本户报错", e);
  			if (e instanceof BusinessException)
  				return new Result(Status.ERROR, e.getMessage());
  			
  			return new Result(Status.ERROR, "商户" + mhtno + "从业务户转账" + CommonUtils.getFenByString(toBaseAccount)+ "至基本户报错，请重试");
  		}
  	}
  	
    /**
     * 查询指定商户的未还款记录
     *
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryNotpaybackByMhtno", method = RequestMethod.GET)
    public Result queryNotpaybackByMhtno(HttpServletRequest request, String mhtno) {
        try {
        	TbMerchantInfo infovo = tbMerchantInfoBaseService.queryInfoByMhtno(mhtno);
            TbSlNotPayBackCreditForFront vo = creditService.queryNotPayback(infovo.getIdOfTbMerchantUser(), null);
            return new Result(Result.Status.OK, vo);
        } catch (Exception e) {
            log.error("查询用户未还贷款数据有误", e);
            return new Result(Result.Status.ERROR, "查询用户未还贷款数据有误");
        }
    }
}

